<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <LimitTech ref="LimitTech" @showTech="openTech" />
      <Tech ref="Tech" @showLimit="openHelp" />
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <el-button
            type="warning"
            size="mini"
            :disabled="draftDisabled"
            @click="draftAction"
          >
            暂存
          </el-button>

          <!-- <el-button
            v-if="workOrdeInfo.id > 0 && workOrdeInfo.status == 0"
            type="warning"
            size="mini"
            @click="recallOrder()"
            :disabled="recallDisabled"
          >
            撤回
          </el-button> -->
          <el-button
            type="primary"
            size="mini"
            :disabled="submitDisabled"
            @click="submitAction"
          >
            提交
          </el-button>
          <!-- <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button> -->

          <!--          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{ name }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span class="primary-color">{{ orderState }}</span>
          </div>-->
          <div class="ml50" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>
      <div id="pdfHtml" class="app-container">
        <el-card class="box-card apply-box">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="mb5"
          />
          <div v-if="dialogVisible" id="printFrom" class="text item">

            <el-card
              class="box-card apply-box mt10 mb20"
            >
              <div slot="header" class="clearfix flex flex-row align-center">
                <div class="line" />
                <span class="font18 ml10 flex-auto">申报者</span>
                <el-button
                  id="no-print"
                  type="danger"
                  round
                  icon="el-icon-thumb"
                  size="small"
                  @click="openHelp"
                >申报指引</el-button>
              </div>
              <el-form
                ref="generateForm"
                label-suffix=":"
                size="small"
                :model="models"
                :rules="rules"
                label-position="right"
                label-width="180px"
              >
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="项目名称"
                      prop="name"
                      label-width="130px"
                    >
                      <el-input
                        v-model="models.name"
                        :style="{width:'100%'}"
                        placeholder="请输入项目名称"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="项目编号"
                      prop="projectNo"
                    >
                      <el-input
                        v-model="models.projectNo"
                        :style="{width:'100%'}"
                        placeholder="请输入项目编号"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="项目分类"
                      prop="projectClass"
                      label-width="130px"
                    >
                      <el-select
                        v-model="models.projectClass"
                        :style="{width:'100%'}"
                        placeholder="请选择项目分类"
                        :filterable="false"
                        clearable
                        value=""
                      >
                        <el-option
                          v-for="(item, index) in [{label:'非限制',value:1},{label:'限制类',value:2}]"
                          :key="index"
                          :value="item.value"
                          :label="item.label"
                        />

                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="申请科室"
                      prop="applyDeptId"
                    >
                      <el-select
                        v-model="models.applyDeptId"
                        :style="{width:'100%'}"
                        placeholder="请选择科室"
                        filterable
                        clearable
                        value=""
                        @change="handleChange"
                      >
                        <el-option
                          v-for="(item, index) in structureList"
                          :key="item.id"
                          :value="item.id"
                          :label="item.depName"
                        />

                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="技术类别"
                      prop="techType"
                      label-width="130px"
                    >
                      <el-cascader
                        v-model="techTypeArr"
                        :options="categoryCatalog"
                        :style="{ width: '100%' }"
                        placeholder="请选择技术类别"
                        :props="{
                          expandTrigger: 'hover',
                          value: 'value',
                          label: 'label'
                        }"
                        clearable
                        @change="handleTechTypeChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="项目负责人"
                      prop="applyManagerName"
                    >
                      <el-input
                        v-model="models.applyManagerName"
                        :style="{width:'100%'}"
                        placeholder="请输入项目负责人"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <!-- <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="项目负责人工号"
                      prop="projectManagerEmp"
                      label-width="130px"
                    >
                      <el-input
                        v-model="models.projectManagerEmp"
                        :style="{width:'100%'}"
                        placeholder="请输入项目负责人工号"
                      />
                    </el-form-item>
                  </el-col> -->
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="负责人联系方式"
                      prop="projectManagerContact"
                      label-width="130px"
                    >
                      <el-input
                        v-model="models.projectManagerContact"
                        :style="{width:'100%'}"
                        placeholder="请输入负责人联系方式"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                  :span="8"
                >
                  <el-form-item
                    label="目标例数"
                    prop="targetNumber"
                  >
                    <el-input
                      v-model="models.targetNumber"
                      :style="{width:'100%'}"
                      placeholder="请输入目标例数"
                      type="number"
                    />
                  </el-form-item>
                </el-col>
                </el-row>
                <el-row
                type="flex"
                :gutter="30"
                justify="start"
                align="top"
              >
                <el-col :span="8">
                  <el-form-item
                    label="项目成员"
                    prop="projectMember"
                    label-width="130px"
                  >
                    <div class="member-input-container">
                      <el-input
                        v-model="selectedMemberText"
                        placeholder="请选择项目成员"
                        readonly
                        type="textarea"
                        :rows="4"
                        :style="{ width: '100%' }"
                        @click.native="openMemberDialog"
                      >
                        <el-button slot="append" icon="el-icon-user" @click="openMemberDialog">选择</el-button>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
                  <el-col
                  :span="8"
                >
                  <el-form-item
                    label="填报人姓名"
                    prop="applyUserName"
                  >
                    <el-input
                      v-model="models.applyUserName"
                      :style="{width:'100%'}"
                      placeholder="请输入填报人姓名"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="填报人工号"
                      prop="workNumber"
                      label-width="130px"
                    >
                      <el-input
                        v-model="models.workNumber"
                        :style="{width:'100%'}"
                        placeholder="请输入工号"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="填报时间"
                      prop="fillTime"
                    >
                      <el-input
                        v-model="models.fillTime"
                        :style="{width:'100%'}"
                        placeholder="请输入项目名称"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <!-- <el-col
                    :span="8"
                  >
                    <el-form-item
                      label="设备或试剂"
                      prop="equipmentReagentsExist"
                    >
                      <el-radio-group
                        v-model="models.equipmentReagentsExist"
                        :style="{ width: 130 }"
                      >
                        <el-radio
                          v-for="(item, index) in [{label:'有',value:1},{label:'无',value:0}]"
                          :key="index"
                          class="incat-radio incat-mini"
                          :style="{display: 'inline-block'}"
                          :label="item.value"
                        >
                          <template>{{ item.label }}</template>
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col> -->
                </el-row>
                <el-row
                type="flex"
                :gutter="30"
                justify="start"
                align="top"
              >
                <el-col
                  :span="16"
                >
                  <el-form-item
                    label="设备名称"
                    prop="deviceNames"
                    label-width="130px"
                  >
                    <el-input
                      type="textarea"
                      :rows="3"
                      placeholder="请输入设备名称"
                      v-model="models.deviceNames"
                      :style="{ width: '62%' }"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
                <!-- <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="备注"
                      prop="remark"
                      label-width="130px"
                    >
                      <el-input
                        v-model="models.remark"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入项目名称"
                        :style="{ width: '62%' }"
                      />
                    </el-form-item>
                  </el-col>
                </el-row> -->
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="申请书"
                      prop="applyDocs"
                      label-width="130px"
                    >
                      <FileUpload :element="uploadConfig" :data-model="models.applyDocs&&JSON.parse(models.applyDocs)" :preview="false" @fileList="fileList" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="设备三证"
                      prop="deviceDocs"
                      label-width="130px"
                    >
                      <FileUpload :element="uploadConfig" :data-model="models.deviceDocs&&JSON.parse(models.deviceDocs)" :preview="false" @fileList="fileList1" />
                    </el-form-item>
                  </el-col>
                </el-row> -->
                <!-- <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="设备三证为"
                      label-width="130px"
                    >
                      <span>*</span>
                      <span
                        :style="{'font-size':'15px','font-weight':'500','color':'#606266'}"
                      >
                        《医疗器械生产企业许可证》、《医疗器械注册证》和《医疗器械经营企业许可证》。
                      </span>
                    </el-form-item>
                  </el-col>
                </el-row> -->
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="补充资料"
                      prop="additionalDocs"
                      label-width="130px"
                    >
                      <FileUpload :element="uploadConfig" :data-model="models.additionalDocs&&JSON.parse(models.additionalDocs)" :preview="false" @fileList="fileList2" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row
                  type="flex"
                  :gutter="30"
                  justify="start"
                  align="top"
                >
                  <el-col
                    :span="16"
                  >
                    <el-form-item
                      label="补充资料说明"
                      label-width="130px"
                    >
                      <div>
                        <span>*</span>
                        <span style="font-size: 15px;font-weight: 400;color:#606266">
                        如有培训证明，请上传
                      </span>
                      </div>
                      <!-- <div>
                        <span>*</span>
                        <span style="font-size: 15px;font-weight: 400;color:#606266">
                        如属本市首次开展的医疗技术，需上传第三方评价机构出具的确认需纳入本市限制类技术目录的评估报告
                      </span>
                      </div> -->
                      <div>
                        <span>*</span>
                        <span style="font-size: 15px;font-weight: 400;color:#606266">
                        其他申请所需材料也可上传为补充资料
                      </span>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>

          </div>
        </el-card>
      </div>
    </el-dialog>
    <LeaderDialog ref="leaderRef" @selectLeader="selectLeader" />

    <!-- 成员选择对话框 -->
    <el-dialog
      title="添加项目成员"
      :visible.sync="memberDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="member-dialog-content">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入关键字搜索"
            prefix-icon="el-icon-search"
            clearable
            @input="handleSearch"
          />
        </div>
        <!-- 部门树形选择 -->
        <div class="tree-container">
          <el-tree
            ref="memberTree"
            :data="departmentUserOptions"
            :props="{
              label: 'name',
              children: 'children'
            }"
            show-checkbox
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            @check="handleTreeCheck"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="data.empNo">({{ data.empNo }})</span>
            </span>
          </el-tree>
        </div>
        <!-- 已选成员展示区 -->
        <!-- <div v-if="selectedMemberNames.length > 0" class="selected-members">
          <div class="selected-title">已选成员：</div>
          <div class="selected-names">
            <el-tag 
              v-for="(name, index) in selectedMemberNames" 
              :key="index"
              size="small"
              closable
              @close="removeMember(index)"
            >
              {{ name }}
            </el-tag>
          </div>
        </div> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelMemberSelect">取 消</el-button>
        <el-button type="primary" @click="confirmMemberSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LimitTech from './limitTech/index.vue'
import LeaderDialog from './leader/index.vue'
import Tech from './tech/index.vue'
import {
  processStructure,
  createWorkOrder,
  draftWorkOrder,
  updateWorkOrder,
  recallWorkOrder, newCreateWorkOrder, newDoUpdate,selectProjectNumbera
} from '@/api/xjs/work-order'
import { listAllUser, newListUser } from '@/api/system/sysuser'
import { getNewDeptInfo, getNewDeptList, getOrdinaryDeptList, newGetUserList, newTreeselect } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
import FileUpload from '@/components/VueFormMaking/components/Upload/file.vue'
import { newGetUserInfo } from '@/api/user'
export default {
  name: 'ApplyDialog',
  components: {
    FileUpload,
    LimitTech,
    Tech,
    LeaderDialog
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadConfig: {
        options: {
          // action: "http://192.168.0.107:8002/api/v1/public/uploadFile?file_type=files"
          defaultValue: [],
          disabled: false,
          length: 9,
          tip: '',
          width: '30%'
        }
      },
      categoryCatalog:[
        {
          value: 1,
          label: '手术操作类',
          children: [
            { value: 11, label: '一级项目（国内医院尚未开展的技术项目）' },
            { value: 12, label: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）' },
            { value: 13, label: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）' },
            { value: 14, label: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）' }
          ]
        },
        {
          value: 2,
          label: '非手术操作类',
          children: [
            { value: 21, label: '一级项目（国内医院尚未开展的技术项目）' },
            { value: 22, label: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）' },
            { value: 23, label: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）' },
            { value: 24, label: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）' }
          ]
        }
      ],
      techTypeArr:[],
      structureList: [],
      structureUserList: [],
      models: {

      },
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      workOrdeInfo: {
        id: null,
        status: 1
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      submitDisabled: false,
      draftDisabled: false,
      recallDisabled: false,
      downloadVisible: false,
      active: 0,
      total: 0,
      processStructureValue: {},
      queryParams: {
        pageIndex: 1,
        pageSize: 5,
        name: undefined
      },
      tpls: [],
      newTpls: [],
      ruleForm: {
        workOrderId: 0,
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: [],
        status: 0
      },
      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        projectNo: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
        projectClass: [{ required: true, message: '请选择项目分类', trigger: 'blur' }],
        applyDeptId: [{ required: true, message: '请选择科室', trigger: 'blur' }],
        techType: [{ required: true, message: '请选择技术类型', trigger: 'blur' }],
        // equipmentReagentsExist: [{ required: true, message: '请选择设备或试剂', trigger: 'blur' }],
        // projectManagerEmp: [{ required: true, message: '请输入项目负责人工号', trigger: 'blur' }],
        projectManagerContact: [{ required: true, message: '请输入负责人联系方式', trigger: 'blur' }],
        targetNumber: [{ required: true, message: '请输入目标例数', trigger: 'blur' }],
        // applyDocs: [{ required: true, message: '请上传申请书', trigger: 'blur' }],
        // deviceDocs: [{ required: true, message: '请上传设备三证', trigger: 'blur' }],
      },
      processId: null,
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      },
      departmentUserOptions: [], // 部门-用户级联数据
      selectedMemberNames: [], // 存储选中的成员姓名
      searchKeyword: '', // 搜索关键字
      memberDialogVisible: false,
      selectedMemberText: '', // 用于显示在输入框中的文本
      tempSelectedMembers: [], // 临时存储选中的成员ID
      tempSelectedNames: [], // 临时存储选中的成员名称
      originalSelectedMembers: [], // 存储打开对话框时的原始选中成员ID
      originalSelectedNames: [], // 存储打开对话框时的原始选中成员名称
    }
  },
  computed: {
    ...mapGetters(['name', 'newUserInfo', 'globalConfig']),
    orderState() {
      if (this.workOrdeInfo.id != null) {
        if (this.workOrdeInfo.status == 1) {
          return '未提交(草稿)'
        } else {
          return `${this.workOrdeInfo.current_state_name}【${
            this.workOrdeInfo.principals
          }】`
        }
      } else {
        return '未提交'
      }
    }
  },
  methods: {
    fileList(files) {
      this.models.applyDocs = JSON.stringify(files)
    },
    fileList1(files) {
      this.models.deviceDocs = JSON.stringify(files)
    },
    fileList2(files) {
      this.models.additionalDocs = JSON.stringify(files)
    },
    getNewDeptListManager(v) {
      // console.log(1111,v)
      getNewDeptList({ pageSize: 1 }).then(response => {
        // console.log(2323,response)
        this.structureUserList = response.records
      })
    },
    getNewDeptTreeList() {
      newTreeselect().then(response => {
        console.log(1122, response.records[0].level)
        this.structureList = response.records[0].level
        // this.deptOptions = response.data
      })
    },
    downLoadDoc(type) {
      var a = document.createElement('a')
      switch (type) {
        case 1:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          break
        case 2:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          break
        case 3:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 4:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 5:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
      }
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    openHelp() {
      this.$refs.Tech.close()
      this.$refs.LimitTech.open()
    },
    openTech() {
      this.$refs.LimitTech.close()
      this.$refs.Tech.open()
    },
    handleChange(v) {
      // getNewDeptInfo({ id: v }).then(res => {
      //   this.models.applyManagerName = res.records[0].deptManagerName
      // })
    },
    guitda(){
      selectProjectNumbera().then(res => {
        this.models.projectNo = res.total.toString()
      })
    },
     // 按部门分组用户
    groupAndDisplayUsers(users) {
      const deptMap = {}
      users.forEach(user => {
        if (!deptMap[user.depID]) {
          deptMap[user.depID] = {
            depID: user.depID,
            depName: user.depName || '未分配部门',
            users: []
          }
        }
        deptMap[user.depID].users.push(user)
      })

      // 部门内部按工号排序
      Object.values(deptMap).forEach(dept => {
        dept.users.sort((a, b) => (a.empNo || '').localeCompare(b.empNo || ''))
      })

      // 部门按名称排序
      this.displayUserGroups = Object.values(deptMap)
        .sort((a, b) => (a.depName || '').localeCompare(b.depName || ''))
        .filter(group => group.users.length > 0)
        
      // 构建级联选择器数据
      this.buildCascaderOptions()
    },
    
    // 构建级联选择器数据
    buildCascaderOptions() {
      this.departmentUserOptions = this.displayUserGroups.map(dept => {
        return {
          id: dept.depID,
          name: dept.depName,
          children: dept.users.map(user => {
            return {
              id: user.id.toString(), // 确保 ID 为字符串类型
              name: user.name,
              empNo: user.empNo,
              depName: user.depName,
              groupName: user.groupName
            }
          })
        }
      })
      
      // 如果有项目成员数据，确保在构建完级联选择器数据后重新设置
      if (this.models && this.models.projectMember && Array.isArray(this.models.projectMember)) {
        console.log('级联选择器数据构建完成，重新设置项目成员:', this.models.projectMember)
        // 使用$nextTick确保DOM更新后再设置值
        this.$nextTick(() => {
          // 强制更新级联选择器的值
          const tempValue = [...this.models.projectMember]
          this.models.projectMember = []
          this.$nextTick(() => {
            this.models.projectMember = tempValue
          })
        })
      }
    },
    
    // 处理成员选择变化
    handleMemberChange(value) {
      console.log('选中的成员ID:', value)
      
      // 检查是否有部门ID被选中
      const selectedDeptIds = value.filter(id => {
        // 检查是否是部门ID（在departmentUserOptions中查找）
        return this.departmentUserOptions && this.departmentUserOptions.some(dept => dept.id === id)
      })
      
      // 如果有部门被选中，添加该部门下的所有人员
      if (selectedDeptIds.length > 0) {
        const allUserIds = new Set(value)
        
        // 遍历选中的部门，添加其下所有人员
        selectedDeptIds.forEach(deptId => {
          const dept = this.departmentUserOptions.find(d => d.id === deptId)
          if (dept && dept.children) {
            dept.children.forEach(user => {
              allUserIds.add(user.id)
            })
          }
        })
        
        // 更新选中的值
        this.models.projectMember = Array.from(allUserIds)
      } else {
        // 如果没有部门被选中，直接使用选中的值
        this.models.projectMember = value
      }
      
      // 更新选中的成员姓名
      this.selectedMemberNames = this.models.projectMember.map(id => {
        // 确保this.allUsers存在且是数组
        if (this.allUsers!= undefined && this.allUsers && Array.isArray(this.allUsers)) {
          const user = this.allUsers.find(u => u.id === id)
          return user ? user.name : ''
        }
        return ''
      }).filter(name => name) // 过滤掉空值
    },
    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: `${this.globalConfig.fullName}医务一网通办`,
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    handleClose(val) {
      this.dialogVisible = false
      this.$refs['ruleForm'].resetFields()
      this.$emit('refreshTable')
    },
      open(row) {
        this.guitda()
        // 先保存传入的数据，避免被覆盖
        const originalData = { ...row }
        console.log('原始数据:', originalData)
        
        newListUser({
          currentPage: 1, 
          pageSize: 10000, // 增大页面大小以获取所有用户
          empNo: null, 
          deptID: "", 
          userID: "", 
          userName: ""
        }).then(res => {
          if (res.records) {
            // 过滤有效数据并保存
            this.allUsers = res.records.filter(user => 
              user.vldFG === '0' && user.name && user.empNo
            )
            
            // 初始化显示所有数据 
            this.groupAndDisplayUsers(this.allUsers)
            
            // 处理项目成员回显
            if (originalData && originalData.projectMember) {
              console.log('原始项目成员数据:', originalData.projectMember)
              // 将字符串格式的成员ID转换为数组
              const memberIds = originalData.projectMember.split(',').filter(id => id)
              console.log('转换后的成员ID数组:', memberIds)
              
              // 确保在设置models.projectMember之前已经构建了departmentUserOptions
              this.$nextTick(() => {
                this.models.projectMember = memberIds
                
                // 更新选中的成员姓名
                this.selectedMemberNames = memberIds.map(id => {
                  const user = this.allUsers.find(u => u.id === Number(id) || u.id === id)
                  return user ? user.name : ''
                }).filter(name => name)
                
                // 更新显示文本
                this.selectedMemberText = this.selectedMemberNames.join('、')
                
                // 保存原始选择状态
                this.originalSelectedMembers = [...this.models.projectMember]
                this.originalSelectedNames = [...this.selectedMemberNames]
                
                console.log('回显项目成员:', this.models.projectMember)
                console.log('回显成员姓名:', this.selectedMemberNames)
              })
            }
          } else {
            console.error('获取用户列表失败:', res)
            this.$message.error('获取用户列表失败')
          }
        })
        Promise.all([newGetUserInfo(), getNewDeptList({ pageSize: 9999 })]).then(resArr => {
          const [userInfoData, deptData] = resArr
          this.models.applyUserName = userInfoData.records[0].name
          this.models.workNumber = userInfoData.records[0].empNo
          this.structureList = deptData.records
          
          // 使用原始数据，避免被覆盖
          this.models = { ...originalData }
          this.techTypeArr = originalData.techType ? originalData.techType.split(',').map(Number) : []
          
          // 确保申请科室正确回显
          if (originalData && originalData.applyDeptId) {
            console.log('申请科室ID:', originalData.applyDeptId)
            // 检查科室ID是否在structureList中存在
            const deptExists = this.structureList.some(dept => dept.id === originalData.applyDeptId)
            if (!deptExists) {
              console.warn('申请科室ID不在科室列表中:', originalData.applyDeptId)
            } else {
              console.log('申请科室ID在科室列表中找到')
            }
            
            // 如果科室存在，获取科室负责人
            if (deptExists) {
              getNewDeptInfo({ id: originalData.applyDeptId }).then(res => {
                if (res.records && res.records.length > 0) {
                  // this.models.applyManagerName = res.records[0].deptManagerName
                  // console.log('设置科室负责人:', this.models.applyManagerName)
                }
              })
            }
          }
          
          // 再次确保项目成员数据正确设置
          if (originalData && originalData.projectMember) {
            const memberIds = originalData.projectMember.split(',').filter(id => id)
            this.models.projectMember = memberIds
            
            // 更新选中的成员姓名
            if(this.allUsers!=undefined&&this.allUsers){
              this.selectedMemberNames = memberIds.map(id => {
              const user = this.allUsers.find(u => u.id === Number(id) || u.id === id)
              return user ? user.name : ''
            }).filter(name => name)
            }
          }
          
          this.dialogVisible = true
          this.$nextTick(() => {
            this.$refs['generateForm'].clearValidate()
          })
        })
      },
    handleLeader() {
      this.$refs.leaderRef.handleInversion()
    },
    getProcessNodeList(row) {
      this.models = row
      this.dialogVisible = true
      /* processStructure({
        processId: this.processId,
        workOrderId: this.ruleForm.workOrderId
      }).then(response => {
        this.processStructureValue = response.data
        this.newTpls = response.data.tpls
        this.currentNode = this.processStructureValue.nodes[0]
        console.log(this.currentNode)
        this.dialogVisible = true
      })*/
    },
    draftAction(item) {
      if (this.workOrdeInfo.id) {
        this.models.id = this.workOrdeInfo.id
      }
      if(this.techTypeArr){
        this.models.techType = this.techTypeArr.join(',')
      }
      if(this.models.projectMember && Array.isArray(this.models.projectMember)) {
        this.models.projectMember = this.models.projectMember.join(',')
      }
      newCreateWorkOrder(this.models).then((res) => {
        this.$message({
          type: 'success',
          message: '暂存成功!'
        })
        if (!this.workOrdeInfo.id) {
          this.workOrdeInfo.id = res.records[0].id
        }
        this.auditStatus = 1
        this.draftDisabled = false
        this.$refs['generateForm'].clearValidate()
        // this.$router.push({ path: '/project/applyList' })
      })
      /* this.draftDisabled = true
      var stateMap = {}
      this.ruleForm.process = this.processId
      this.ruleForm.status = 1
      this.ruleForm.classify = this.processStructureValue.process.classify
      stateMap['id'] = item.target
      this.ruleForm.source_state = this.processStructureValue.nodes[
        this.active
      ].label

      for (var v of this.processStructureValue.nodes) {
        if (v.id === item.target) {
          if (v.assignType !== undefined) {
            stateMap['process_method'] = v.assignType
          }
          if (v.assignValue !== undefined) {
            stateMap['processor'] = Array.from(new Set(v.assignValue))
          }
          stateMap['label'] = v.label
          stateMap['desc'] = v.desc
          break
        }
      }
      this.ruleForm.state = [stateMap]

      this.ruleForm.tpls = {
        form_name: [],
        form_structure: [],
        form_data: []
      }

      var promiseList = []

      this.tpls = []
      for (var tpl of this.newTpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
      }

      for (var tpl of this.processStructureValue.tpls) {
        // tpl.form_structure.id = tpl.id;
        this.ruleForm.tpls.form_structure.push(tpl.form_structure)
        this.ruleForm.tpls.form_name.push(tpl.form_name)
        promiseList.push(
          this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
        )
      }

      Promise.all(promiseList)
        .then(values => {
          this.ruleForm.source = this.processStructureValue.nodes[
            this.active
          ].id
          console.log(values)
          for (var item of values) {
            if (item.hasOwnProperty('project_name')) {
              this.ruleForm.title = item.project_name
            }
          }
          if (this.tpls.length > 0) {
            for (var tplDataIndex in this.tpls) {
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }
            this.ruleForm.newTpls = this.tpls
          }

          this.ruleForm.tpls.form_data = values
          this.ruleForm.is_exec_task = item.isExecuteTask
          draftWorkOrder(this.ruleForm)
            .then(response => {
              if (response.code === 200) {
                console.log(response)
                this.$message({
                  type: 'success',
                  message: '暂存成功!'
                })
                this.workOrdeInfo = response.data.workOrder
                this.ruleForm.workOrderId = this.workOrdeInfo.id
                this.newTpls = response.data.tpls
                this.draftDisabled = false
                console.log(this.processStructureValue.tpls)
              }
            })
            .catch(() => {
              this.draftDisabled = false
            })
        })
        .catch(() => {
          this.draftDisabled = false
        })*/
    },

    selectLeader(userId) {
      this.ruleForm.state[0]['processor'] = [userId]
      updateWorkOrder(this.ruleForm)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.handleClose()
            // this.$router.push({ path: "/project/applyList" });
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.submitDisabled = false
        })
    },
    recallOrder() {
      this.recallDisabled = true
      const recallParams = {
        work_oroder_id: this.workOrdeInfo.id,
        process_id: this.workOrdeInfo.process
      }
      recallWorkOrder(recallParams)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.recallDisabled = false
            this.submitDisabled = false
            this.recallStatus = 1
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.submitDisabled = false
          this.recallDisabled = false
        })
    },
    submitAction() {
      this.$refs['generateForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if(this.techTypeArr){
            this.models.techType = this.techTypeArr.join(',')
          }
          if(this.models.projectMember && Array.isArray(this.models.projectMember)) {
            this.models.projectMember = this.models.projectMember.join(',')
          }
          newDoUpdate({ id: this.workOrdeInfo.id || this.models.id }).then(res => {
            // console.log("提交",res)

            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            // this.auditStatus = 2
            this.submitDisabled = false
            this.handleClose()
            loading.close()
          })
        }
      })
      /* newCreateWorkOrder(this.models).then((res)=>{
        const id = res.records[0].id;
        newDoUpdate({id}).then(res=>{

          console.log("提交",res)

          this.$message({
            type: 'success',
            message: '提交成功!'
          })
          // this.auditStatus = 2
          this.submitDisabled = false
          this.handleClose()

        })

      })*/
      /* this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.submitDisabled = true
          var stateMap = {}
          this.ruleForm.process = this.processId
          this.ruleForm.status = 0
          this.ruleForm.classify = this.processStructureValue.process.classify
          stateMap['id'] = item.target
          this.ruleForm.source_state = this.processStructureValue.nodes[
            this.active
          ].label
          for (var v of this.processStructureValue.nodes) {
            if (v.id === item.target) {
              if (v.assignType !== undefined) {
                stateMap['process_method'] = v.assignType
              }
              if (v.assignValue !== undefined) {
                stateMap['processor'] = Array.from(new Set(v.assignValue))
              }
              stateMap['label'] = v.label
              stateMap['desc'] = v.desc
              break
            }
          }
          this.ruleForm.state = [stateMap]

          this.ruleForm.tpls = {
            form_name: [],
            form_structure: [],
            form_data: []
          }

          var promiseList = []

          this.tpls = []
          for (var tpl of this.newTpls) {
            this.tpls.push({
              tplDataId: tpl.id,
              tplId: tpl.form_structure.id
            })
          }

          for (var tpl of this.processStructureValue.tpls) {
            // tpl.form_structure.id = tpl.id;
            this.ruleForm.tpls.form_structure.push(tpl.form_structure)
            this.ruleForm.tpls.form_name.push(tpl.form_name)
            promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
          }
          Promise.all(promiseList)
            .then(values => {
              this.ruleForm.source = this.processStructureValue.nodes[
                this.active
              ].id
              let leadId = 0
              for (var item of values) {
                if (item.hasOwnProperty('project_name')) {
                  this.ruleForm.title = item.project_name
                }
                if (item.hasOwnProperty('leader_name')) {
                  leadId = item.leader_name
                }
              }
              if (this.tpls.length > 0) {
                for (var tplDataIndex in this.tpls) {
                  this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
                }
                this.ruleForm.newTpls = this.tpls
              }
              this.ruleForm.tpls.form_data = values
              this.ruleForm.is_exec_task = item.isExecuteTask

              // this.handleLeader();
              this.selectLeader(leadId)
              this.submitDisabled = false
            })
            .catch(() => {
              this.submitDisabled = false
            })
        }
      })*/
    },
    // 搜索过滤方法
    filterNode(value, data) {
      if (!value) return true
      return data.name.toLowerCase().indexOf(value.toLowerCase()) !== -1 ||
             (data.empNo && data.empNo.toLowerCase().indexOf(value.toLowerCase()) !== -1)
    },
    
    // 处理搜索输入
    handleSearch(value) {
      this.$refs.memberTree.filter(value)
    },
    
    // 处理树形选择
    handleTreeCheck(data, checked) {
      const checkedNodes = this.$refs.memberTree.getCheckedNodes()
      // 过滤出用户节点（有empNo的节点）
      const selectedUsers = checkedNodes.filter(node => node.empNo)
      
      this.tempSelectedMembers = selectedUsers.map(user => user.id.toString()) // 确保 ID 为字符串
      this.tempSelectedNames = selectedUsers.map(user => user.name)
    },
    
    // 移除成员
    removeMember(index) {
      const memberId = this.tempSelectedMembers[index]
      this.tempSelectedMembers.splice(index, 1)
      this.tempSelectedNames.splice(index, 1)
      // 更新树的选中状态
      this.$refs.memberTree.setChecked(memberId, false, false)
    },
    // 打开成员选择对话框
    openMemberDialog() {
      // 保存当前的选择状态
      this.originalSelectedMembers = [...this.models.projectMember]
      this.originalSelectedNames = [...this.selectedMemberNames]
      
      // 初始化临时选择状态
      this.tempSelectedMembers = [...this.models.projectMember]
      this.tempSelectedNames = [...this.selectedMemberNames]
      
      this.memberDialogVisible = true
      
      // 在下一个 tick 设置树的选中状态
      this.$nextTick(() => {
        if (this.$refs.memberTree) {
          // 先清空所有选中状态
          this.$refs.memberTree.setCheckedKeys([])
          // 设置原始选中状态
          this.originalSelectedMembers.forEach(id => {
            this.$refs.memberTree.setChecked(id, true, false)
          })
        }
      })
    },
    // 取消选择
    cancelMemberSelect() {
      // 恢复到原始选择状态
      this.models.projectMember = [...this.originalSelectedMembers]
      this.selectedMemberNames = [...this.originalSelectedNames]
      this.selectedMemberText = this.originalSelectedNames.join('、')
      
      // 关闭对话框
      this.memberDialogVisible = false
      
      // 重置临时存储的数据
      this.tempSelectedMembers = []
      this.tempSelectedNames = []
      this.searchKeyword = ''
    },
    // 确认选择
    confirmMemberSelect() {
      // 更新选择结果
      this.models.projectMember = [...this.tempSelectedMembers]
      this.selectedMemberNames = [...this.tempSelectedNames]
      this.selectedMemberText = this.selectedMemberNames.join('、')
      
      // 关闭对话框
      this.memberDialogVisible = false
      
      // 重置临时数据
      this.tempSelectedMembers = []
      this.tempSelectedNames = []
      this.searchKeyword = ''
    },
    // 监听对话框关闭
    handleDialogClose() {
      this.cancelMemberSelect()
    },
    // 确保 ID 类型一致的辅助方法
    normalizeId(id) {
      return id.toString()
    },
    // 处理技术类别变化
    handleTechTypeChange(value) {
      console.log('技术类别选择:', value)
      this.models.techType = value ? value.join(',') : ''
    },
  },
  watch: {
    selectedMemberNames: {
      immediate: true,
      handler(val) {
        this.selectedMemberText = val.join('、')
      }
    },
    // 监听对话框可见性
    memberDialogVisible(newVal) {
      if (!newVal) {
        // 对话框关闭时重置搜索关键字
        this.searchKeyword = ''
      }
    },
    // 监听 listData 变化
    listData: {
      handler(newVal) {
        if (newVal && newVal.projectMember) {
          const memberIds = newVal.projectMember.split(',').filter(id => id)
          this.models.projectMember = memberIds
          
          // 如果已经有用户数据，立即更新选中状态
          if (this.allUsers.length > 0) {
            this.selectedMemberNames = memberIds.map(id => {
              const user = this.allUsers.find(u => u.id === Number(id) || u.id === id)
              return user ? user.name : ''
            }).filter(name => name)
            this.selectedMemberText = this.selectedMemberNames.join('、')
          }
        }
      },
      immediate: true
    },
    // 监听 listData 变化，处理技术类别回显
    'listData.techType': {
      handler(newVal) {
        if (newVal) {
          const techTypes = newVal.split(',').map(Number)
          console.log('监听到技术类别变化:', techTypes)
          this.techTypeArr = techTypes
        } else {
          this.techTypeArr = []
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
/* 修改容器样式 */
.apply-dialog {
  height: 100%;
  
  ::v-deep .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    
    .el-dialog__header {
      padding: 15px 20px;
    }
    
    .el-dialog__body {
      flex: 1;
      overflow-y: auto;
      padding: 0;
    }
  }
}

.app-container {
  padding: 10px 20px;
  background: #ebf4fa;
  height: 100%;
  box-sizing: border-box;
  
  .apply-box {
    border-radius: 15px;
    margin-bottom: 0; // 移除底部边距
    
    ::v-deep .el-card__body {
      padding-bottom: 20px; // 调整卡片内容底部padding
    }
    
    .line {
      height: 22px;
      width: 5px;
      background: #277fd6;
    }
  }
}

/* 调整表单布局 */
::v-deep .el-form {
  .el-form-item {
    margin-bottom: 18px; // 适当减小表单项之间的间距
    
    &:last-child {
      margin-bottom: 0; // 最后一个表单项不要底部边距
    }
  }
}

/* 成员选择对话框样式 */
.member-dialog-content {
  .tree-container {
    height: 300px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    overflow-y: auto;
  }
}

/* 其他样式保持不变... */

/* 文件上传区域样式调整 */
::v-deep .upload-container {
  margin-bottom: 0;
}

/* 调整按钮和标题栏样式 */
.flex {
  &.flex-row {
    &.align-center {
      padding: 0 10px;
      
      .btn-list {
        display: flex;
        align-items: center;
        
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

/* 调整表单行间距 */
.el-row {
  margin-bottom: 15px !important;
  
  &:last-child {
    margin-bottom: 0 !important;
  }
}

/* 调整补充说明文字样式 */
.selected-title, 
.font14 {
  margin: 5px 0;
  line-height: 1.4;
}

/* 文件上传组件底部间距调整 */
::v-deep .el-upload {
  margin-bottom: 0;
}

/* 确保滚动条美观 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 确保级联选择器样式正确 */
::v-deep .el-cascader {
  width: 100%;
  
  .el-input {
    width: 100%;
  }
}

/* 调整级联选择器下拉面板的样式 */
::v-deep .el-cascader__dropdown {
  .el-cascader-panel {
    .el-cascader-menu {
      min-width: 200px;  // 增加选项宽度
      
      .el-cascader-menu__item {
        padding: 8px 20px;  // 增加选项内边距
        line-height: 1.5;
      }
    }
  }
}
</style>

